package com.fan.shop.dao;

import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.fan.shop.domain.TransactionReference;
import com.fan.shop.domain.TransactionReferenceGroup;

@Named("transactionReferenceGroupDao")
public class TransactionReferenceGroupDaoImpl implements
		TransactionReferenceGroupDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public List<TransactionReferenceGroup> getAllTransactionReferencesGroups() {
		List<TransactionReferenceGroup> list = sessionFactory
				.getCurrentSession()
				.createCriteria(TransactionReferenceGroup.class).list();
		return list;
	}

	public TransactionReferenceGroup getTransactionReferenceGroup(String name) {
		TransactionReferenceGroup transactionReferenceGroup = (TransactionReferenceGroup) sessionFactory
				.getCurrentSession().get(TransactionReferenceGroup.class, name);
		return transactionReferenceGroup;
	}

	public boolean hasTransactionReferenceGroup(String name) {
		if (getTransactionReferenceGroup(name) == null) {
			return false;
		}
		else
		{
			return true;
		}
	}

	public int getSize() {
		return getAllTransactionReferencesGroups().size();
	}

	public void addTransactionReferenceGroup(
			TransactionReferenceGroup transactionReferenceGroup) {
		sessionFactory.getCurrentSession().save(transactionReferenceGroup);

	}

	public void updateTransactionReferenceGroup(
			TransactionReferenceGroup transactionReferenceGroup) {
		sessionFactory.getCurrentSession().update(transactionReferenceGroup);

	}

	public void deleteTransactionReferenceGroup(
			TransactionReferenceGroup transactionReferenceGroup) {
		sessionFactory.getCurrentSession().delete(transactionReferenceGroup);

	}

	@SuppressWarnings("unchecked")
	public List<String> getColumnNames() {
		List<String> columns = sessionFactory
				.getCurrentSession()
				.createSQLQuery(
						"SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TRANSACTION_REFERENCE_GROUP'")
				.list();

		return columns;
	}

	@SuppressWarnings("unchecked")
	public List<TransactionReference> getSubTransactionReferences(String groupCode) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TransactionReference.class);
		criteria.add(Restrictions.eq("groupCode", groupCode));
		List<TransactionReference> list= criteria.list();
		return list;
	}

}
